package com.xhtranslate.service.ali.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeAdvancedRequest;
import com.aliyun.ocr_api20210707.models.RecognizeAdvancedResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.xhtranslate.common.config.TranslateConfig;
import com.xhtranslate.common.util.FileUtil;
import com.xhtranslate.common.util.AddUseLimitThreadUtil;
import com.xhtranslate.service.ali.service.AliOcrService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;

/**
 * 阿里ocr服务impl
 *
 * @author liuxuhuang
 * @date 2022/11/20 16:23:29
 */
@Service
@Slf4j
public class AliOcrServiceImpl implements AliOcrService {
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    @Qualifier(value = "ocrBean")
    private Client ocrClient;
    @Autowired
    private AddUseLimitThreadUtil addUseLimitThreadUtil;

    @Override
    public String ocrImg(MultipartFile file) throws Exception {
        File saveImg = fileUtil.saveImg(file);
        FileInputStream inputStream = new FileInputStream(saveImg);
        RecognizeAdvancedRequest recognizeAdvancedRequest = new RecognizeAdvancedRequest()
                .setBody(inputStream)
                .setNeedSortPage(true)
                .setRow(true)
                .setParagraph(true)
                .setNoStamp(true)
                .setOutputFigure(true);
        RuntimeOptions options = new RuntimeOptions();
        RecognizeAdvancedResponse response = ocrClient.recognizeAdvancedWithOptions(recognizeAdvancedRequest, options);
        JSONObject jsonObject = JSONObject.parseObject(String.valueOf(JSON.toJSON(response)));
        int code = jsonObject.getInteger("statusCode");
        if (code != 200) {
            return "";
        }
        JSONArray jsonArray = jsonObject.getJSONObject("body").getJSONObject("data").getJSONArray("prism_rowsInfo");
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < jsonArray.size(); i++) {
            String words = jsonArray.getJSONObject(i).getString("word");
            stringBuffer.append(words).append("\n");
        }
        addUseLimitThreadUtil.addCreditLimit(TranslateConfig.AliOcrRedisName, 1);
        String string = stringBuffer.toString();
        log.info("阿里ocr识别结果");
        log.info(string);
        return string;
    }
}
